package com.huichenghe.xinlvsh01.fragment;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.huichenghe.xinlvsh01.Adapter.HistogramAdapter;
import com.huichenghe.xinlvsh01.Adapter.RecyclerViewAdapterForMovementDetail;
import com.huichenghe.xinlvsh01.Adapter.SuperAdapter;
import com.huichenghe.xinlvsh01.CustomView.HeartReatDetailsView;
import com.huichenghe.xinlvsh01.CustomView.HorizontalListView;
import com.huichenghe.xinlvsh01.DbEntities.MyDBHelperForDayData;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.Utils.ZhuzhuangtuEntity;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MovementFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MovementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MovementFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters，参数名和类型，根据具体需要而定
    private String mParam1;
    private String mParam2;
    private HorizontalListView horizontalListView, mCalorieListView;
    private Context mContext;       // 上下文对象
    private ArrayList<ZhuzhuangtuEntity> mList;
    private HistogramAdapter mHistogramAdapter, mCalorieAdapter;

    private LinearLayout mStepSelect, mCalorieSelect;
    private ImageView mButtonStep, mButtonCalorie;

    private TextView sitTimeTV, moveTimeTV, sitCalorieTV, moveCalorieTV;
    private HeartReatDetailsView mDayTimeView;

    private OnFragmentInteractionListener mListener;

    /**
     * 通过此方法创建Fragment实例，并传递需要的数据
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MovementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MovementFragment newInstance(String param1, String param2) {
        MovementFragment fragment = new MovementFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public MovementFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }


    @Override
    public void onResume()
    {
        super.onResume();
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DATE);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        String date = year + "-" + month + "-" + day;
        String userAccount = LocalDataSaveTool.getInstance(mContext).readSp(MyConfingInfo.USER_ACCOUNT);
        // 查询分时计步数据
        Cursor cursor = MyDBHelperForDayData.getInstance(mContext).getEachHourData(mContext, userAccount, date);
        // 解析并显示
        parserTheCursor(cursor, mHistogramAdapter);

        // 查询分时热量数据
        Cursor mmCursor1 = MyDBHelperForDayData.getInstance(mContext).getEachHourCalorieData(mContext, userAccount, date);
        // 解析并显示

        parserTheCursor(mmCursor1, mCalorieAdapter);

        // 查询天数据
        Cursor cursor1 = MyDBHelperForDayData.getInstance(mContext).selecteDayData(mContext, userAccount, date);
        parserTheCursor(cursor1);


        // 查询心率数据
        String hex = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005651565156534e564e514e58584e514e565358584e4c5158515656585e5b5851534e535151534e4e565353565351584856514c5353514e4c585856565b5e535656565658535358535358515658535853585858514e4e4e56585656514c514e51514c4e534c514e564e4e534e4c515300585b585b5858584e564e5358585b58585b5858585858585653585b585b5b5b565b565b5158535b5658585b5b5b5858515b5b53585b585b585853565656585658585b53565b5853585b004a535851564a514c4c484e4a4a514c4a53514c514c47564e4c5653514e4c4e5658514e585353514e4e4a564c48514c4a4c514e4c4a4e4c51514e534e515353534e535153534c565353534e4e5151535158534e534e4e535351535156534a56514c5353565156585158534e53585151534e534c5151565b534e535351564c53564c4e51534a534e53515153584e56515353535853514e53534e56565858564e514e4a5151584e5653535358534e5158515348535156535b5151565356514e4e565856585153534e530056004c5858565b484e00584e514a4a514c564c4a514c4c484e004e474c4a474a4a5147474c4548004a56534e4e4e514a4c4c455100004c4e514c4c004c004c4e534c4e484e4c48";
        // 添加心率曲线数据
        mDayTimeView.setData(100, 190, hex, 220);
        mDayTimeView.invalidate();


    }


    /***
     * 解析全天数据的cursor
     * @param cursor1
     */
    private void parserTheCursor(Cursor cursor1)
    {
        if(cursor1.getCount() > 0)
        {
            if(cursor1.moveToFirst())
            {
                String movementTime = cursor1.getString(cursor1.getColumnIndex("movementTime"));
                String sitTime = cursor1.getString(cursor1.getColumnIndex("sitTime"));
                int moveCalorie = cursor1.getInt(cursor1.getColumnIndex("moveCalorie"));
                int sitCalorie = cursor1.getInt(cursor1.getColumnIndex("sitCalorie"));

                int moveTi = Integer.parseInt(movementTime);
                int sitTi = Integer.parseInt(sitTime);
                int hourM = moveTi / 60;
                int minuteM = moveTi % 60;
                int hourS = sitTi / 60;
                int minuteS = sitTi % 60;

                movementTime = hourM + "h" + minuteM + "'";
                sitTime = hourS + "h" + minuteS + "'";




                sitTimeTV.setText(sitTime);
                moveTimeTV.setText(movementTime);
                moveCalorieTV.setText(moveCalorie + "");
                sitCalorieTV.setText(sitCalorie + "");





            }
        }
    }


    /**
     * 解析查询出的数据游标对象
     * @param cursor
     */
    private void parserTheCursor(Cursor cursor, HistogramAdapter adapter)
    {
        if(cursor.getCount() != 0)
        {
            if(cursor.moveToFirst())
            {
                do{
                    int[] steps = new int[24];
                    int stepOne = cursor.getInt(cursor.getColumnIndex("one"));
                    int stepTwo = cursor.getInt(cursor.getColumnIndex("two"));
                    int stepThree = cursor.getInt(cursor.getColumnIndex("three"));
                    int stepFour = cursor.getInt(cursor.getColumnIndex("four"));
                    int stepFive = cursor.getInt(cursor.getColumnIndex("five"));
                    int stepSix = cursor.getInt(cursor.getColumnIndex("six"));
                    int stepSeven = cursor.getInt(cursor.getColumnIndex("seven"));
                    int stepEight = cursor.getInt(cursor.getColumnIndex("eight"));
                    int stepNine = cursor.getInt(cursor.getColumnIndex("nine"));
                    int stepTen = cursor.getInt(cursor.getColumnIndex("ten"));
                    int stepOne1 = cursor.getInt(cursor.getColumnIndex("one1"));
                    int stepTwo1 = cursor.getInt(cursor.getColumnIndex("two1"));
                    int stepThree1 = cursor.getInt(cursor.getColumnIndex("three1"));
                    int stepFour1 = cursor.getInt(cursor.getColumnIndex("four1"));
                    int stepFive1 = cursor.getInt(cursor.getColumnIndex("five1"));
                    int stepSix1 = cursor.getInt(cursor.getColumnIndex("six1"));
                    int stepSeven1 = cursor.getInt(cursor.getColumnIndex("seven1"));
                    int stepEight1 = cursor.getInt(cursor.getColumnIndex("eight1"));
                    int stepNine1 = cursor.getInt(cursor.getColumnIndex("nine1"));
                    int stepTen1 = cursor.getInt(cursor.getColumnIndex("ten1"));
                    int stepOne2 = cursor.getInt(cursor.getColumnIndex("one2"));
                    int stepTwo2 = cursor.getInt(cursor.getColumnIndex("two2"));
                    int stepThree2 = cursor.getInt(cursor.getColumnIndex("three2"));
                    int stepFour2 = cursor.getInt(cursor.getColumnIndex("four2"));

                    steps[0] = stepOne;
                    steps[1] = stepTwo;
                    steps[2] = stepThree;
                    steps[3] = stepFour;
                    steps[4] = stepFive;
                    steps[5] = stepSix;
                    steps[6] = stepSeven;
                    steps[7] = stepEight;
                    steps[8] = stepNine;
                    steps[9] = stepTen;
                    steps[10] = stepOne1;
                    steps[11] = stepTwo1;
                    steps[12] = stepThree1;
                    steps[13] = stepFour1;
                    steps[14] = stepFive1;
                    steps[15] = stepSix1;
                    steps[16] = stepSeven1;
                    steps[17] = stepEight1;
                    steps[18] = stepNine1;
                    steps[19] = stepTen1;
                    steps[20] = stepOne2;
                    steps[21] = stepTwo2;
                    steps[22] = stepThree2;
                    steps[23] = stepFour2;
                    // 取数组最大值

                    int bigMax = getTheMaxInt(steps);
                    for (int i = 0; i < steps.length; i ++)
                    {
                        if(steps[i] >= 0)
                        {
                            adapter.addStepItem(i + ":00", steps[i], bigMax);
                        }
                    }

                }while (cursor.moveToNext());

                adapter.notifyDataSetChanged();
            }
        }





    }


    /**
     * 取数组的最大值
     * @param steps
     */
    private int getTheMaxInt(int[] steps)
    {
        int max = 0;
        for (int i = 0; i < steps.length; i ++)
        {
            if(steps[i] > steps[max])
            {
                max = i;
            }
        }
        return steps[max];
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_movement, container, false);
        mDayTimeView = (HeartReatDetailsView)v.findViewById(R.id.daytime_hr);

//        mList = new ArrayList<ZhuzhuangtuEntity>();
//        mList.add(new ZhuzhuangtuEntity("10:10", 500, 1000));
//        mList.add(new ZhuzhuangtuEntity("12:12", 600, 1000));
//        mList.add(new ZhuzhuangtuEntity("13:15", 700, 1000));


        mCalorieListView = (HorizontalListView)v.findViewById(R.id.calorie_show_each_hour);
        ViewTreeObserver caTree = mCalorieListView.getViewTreeObserver();
        mCalorieAdapter = new HistogramAdapter(mContext, mCalorieListView.getMeasuredHeight());
        caTree.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mCalorieListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int hh = mCalorieListView.getHeight();
                mCalorieAdapter.initWH(hh);
            }
        });
        mCalorieListView.setAdapter(mCalorieAdapter);



        horizontalListView = (HorizontalListView)v.findViewById(R.id.stpe_show_each_hour);
        ViewTreeObserver tree = horizontalListView.getViewTreeObserver();
        mHistogramAdapter = new HistogramAdapter(mContext, horizontalListView.getMeasuredHeight());
        tree.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                horizontalListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int h = horizontalListView.getHeight();
                mHistogramAdapter.initWH(h);
            }
        });
        horizontalListView.setAdapter(mHistogramAdapter);
        mStepSelect = (LinearLayout)v.findViewById(R.id.setp_select);
        mCalorieSelect = (LinearLayout)v.findViewById(R.id.calorie_select);
        mButtonStep = (ImageView)v.findViewById(R.id.button_step);
        mButtonCalorie = (ImageView)v.findViewById(R.id.button_calorie);
        mStepSelect.setOnClickListener(listener);
        mCalorieSelect.setOnClickListener(listener);

//        mHistogramAdapter.addStepItem("10:10", 800, 10000);
//        mHistogramAdapter.addStepItem("12:12", 6000, 10000);
//        mHistogramAdapter.addStepItem("13:15", 10000, 10000);
//        mHistogramAdapter.notifyDataSetChanged();

//        mCalorieAdapter.addStepItem("8:00", 300, 1500);
//        mCalorieAdapter.addStepItem("9:00", 800, 1500);
//        mCalorieAdapter.addStepItem("10:00", 1000, 1500);
//        mCalorieAdapter.notifyDataSetChanged();

        sitTimeTV = (TextView)v.findViewById(R.id.sitTime);
        moveTimeTV = (TextView)v.findViewById(R.id.moveTime);
        sitCalorieTV = (TextView)v.findViewById(R.id.sitCalorie);
        moveCalorieTV = (TextView)v.findViewById(R.id.moveCalorie);







        return v;
    }


    boolean isStep = true;
    View.OnClickListener listener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.setp_select:
                    if(isStep)
                    {
                        // do nothing
                    }
                    else
                    {
                        mButtonStep.setImageResource(R.drawable.has_focus);
                        mButtonCalorie.setImageResource(R.drawable.not_focos);
                        horizontalListView.setVisibility(View.VISIBLE);
                        mCalorieListView.setVisibility(View.INVISIBLE);
                        isStep = true;
                    }
                    break;
                case R.id.calorie_select:
                    if(isStep)
                    {
                        mButtonCalorie.setImageResource(R.drawable.has_focus);
                        mButtonStep.setImageResource(R.drawable.not_focos);
                        horizontalListView.setVisibility(View.INVISIBLE);
                        mCalorieListView.setVisibility(View.VISIBLE);



                        isStep = false;
                    }
                    else
                    {
//                        do nothing
                    }
                    break;
            }
        }
    };

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = (Context)activity;
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    // 在onDestroy后调用
    @Override
    public void onDetach()
    {
        super.onDetach();
        mListener = null;
    }

    /**
     * 此借口常用于fragment间通信
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }


    /**
     * 更新白天数据
     * @param day
     */
    public void updateDayData(String day)
    {
        String userAccount = LocalDataSaveTool.getInstance(mContext).readSp(MyConfingInfo.USER_ACCOUNT);
        // 查询计步
        Cursor mCursor = MyDBHelperForDayData.getInstance(mContext).getEachHourData(mContext, userAccount, day);
        parserTheCursor(mCursor, mHistogramAdapter);
        // 查询卡路里
        Cursor cursor = MyDBHelperForDayData.getInstance(mContext).getEachHourCalorieData(mContext, userAccount, day);
        parserTheCursor(cursor, mCalorieAdapter);

    }



}
